//
//  SearchViewController.m
//  FDSMeshLibDemo
//
//  Created by LEIPENG on 2022/6/10.
//

#import "SearchViewController.h"
#import "SearchDeviceTableViewCell.h"

@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) MeshTool *meshTool;
@property (nonatomic, strong) NSTimer *checkTimer;
@property (nonatomic, strong) NSMutableArray *peripheralList;
@property (nonatomic, strong) NSMutableArray *selectDeviceList;

@property (weak, nonatomic) IBOutlet UILabel *scanLabel;
@property (weak, nonatomic) IBOutlet UIButton *configButton;
@property (weak, nonatomic) IBOutlet UITableView *tableview;


@end

@implementation SearchViewController

#pragma mark - Initialize
- (void)InitializeCode{
    self.title = @"搜索设备";
    self.meshTool = [MeshTool shareInstance];
    self.peripheralList = [NSMutableArray array];
    self.selectDeviceList = [NSMutableArray array];
    self.configButton.layer.cornerRadius = 22;
    self.configButton.layer.masksToBounds = YES;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"setting_09"] style:(UIBarButtonItemStylePlain) target:self action:@selector(clickRefreshItem)];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self InitializeCode];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self startScanMeshDevice];
    self.checkTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(checkTimeRun) userInfo:nil repeats:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.checkTimer) {
        [self.checkTimer invalidate];
        self.checkTimer = nil;
    }
    [FDSMeshApi stopScan];
}
#pragma mark - NSTimer
- (void)checkTimeRun{
    // 当前页面-每5秒检测一次是否正在扫描1827设备，如果没有扫描则需要重新调用扫描接口
    if ([FDSMeshApi isEnableScanProvisionedDevices]) {
        NSLog(@"需要调用扫描接口");
        [self startScanMeshDevice];
    }
}

#pragma mark - UIButton
- (void)clickRefreshItem{
    self.scanLabel.text = @"可连接设备";
    [self.selectDeviceList removeAllObjects];
    [self.peripheralList removeAllObjects];
    [self.tableview reloadData];
    [self startScanMeshDevice];
}
- (void)startScanMeshDevice{
    // 扫描Mesh设备
    [FDSMeshApi startScanDevice:@"GD_LED" completion:^(CBPeripheral * _Nonnull peripheral) {
        if (self.meshTool.meshModel.isFastProvision) {
            // Fast Proviosn需要限制固件版本为000055以上
            if (([peripheral.device_firmwareVersion compare:@"000055"] != NSOrderedAscending)) {
                if (![self.peripheralList containsObject:peripheral]) {
                    [self.peripheralList addObject:peripheral];
                    self.scanLabel.text = [NSString stringWithFormat:@"可连接设备：%lu",(unsigned long)self.peripheralList.count];
                    [self.tableview reloadData];
                }
            }
        } else {
            if (![self.peripheralList containsObject:peripheral]) {
                [self.peripheralList addObject:peripheral];
                self.scanLabel.text = [NSString stringWithFormat:@"可连接设备：%lu",(unsigned long)self.peripheralList.count];
                [self.tableview reloadData];
            }
        }
    }];
}
- (IBAction)clickConfigMeshBtn:(UIButton *)sender {
    // 设备组网
    if (self.selectDeviceList.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"未选中设备！"];
    } else {
        [self.meshTool refreshNodesAndGroups];
        if (self.meshTool.nodeList.count + self.selectDeviceList.count > 200) {
            [SVProgressHUD showErrorWithStatus:@"即将超过上限200的节点！"];
            return;
        }
        NSLog(@"开始组网 ---> 总数：%lu",(unsigned long)self.selectDeviceList.count);
        [FDSMeshApi filterAutoConnectedNode:@[]];
        if (self.meshTool.meshModel.isFastProvision) {
            [self startFastProvision:self.selectDeviceList];
        } else {
            NSMutableArray *oldDeviceList = [NSMutableArray array];
            NSMutableArray *newDeviceList = [NSMutableArray array];
            for (CBPeripheral *peripheral in self.selectDeviceList) {
                if (([peripheral.device_firmwareVersion compare:@"000055"] != NSOrderedAscending)) {
                    [newDeviceList addObject:peripheral];
                } else {
                    [oldDeviceList addObject:peripheral];
                }
            }
            __block NSInteger progressIndex = 0;
            __block NSInteger failedIndex = 0;
            __block NSTimeInterval beginTime = [[NSDate date] timeIntervalSince1970];
            [SVProgressHUD showProgress:0 status:[NSString stringWithFormat:@"进度：%ld/%lu，失败：%ld",(long)progressIndex, (unsigned long)oldDeviceList.count, (long)failedIndex]];
            [FDSMeshApi startAddDeviceToNetWork:oldDeviceList progressAction:^(BOOL success, CBPeripheral * _Nonnull peripheral) {
                NSLog(@"节点组网 ---> 节点(%@)：%@",peripheral.device_name,success?@"组网成功":@"组网失败");
                progressIndex++;
                if (!success) {
                    failedIndex++;
                }
                CGFloat progressPercent = (CGFloat)progressIndex/oldDeviceList.count;
                [SVProgressHUD showProgress:progressPercent status:[NSString stringWithFormat:@"进度：%ld/%lu，失败：%ld",(long)progressIndex, (unsigned long)oldDeviceList.count, (long)failedIndex]];
            } resultAction:^(BOOL finish, NSArray * _Nonnull addrList) {
                if (newDeviceList.count) {
                    [self startFastProvision:newDeviceList];
                } else {
                    NSInteger count = addrList.count;
                    NSTimeInterval endTime = [[NSDate date] timeIntervalSince1970];
                    NSString *resultTips = [NSString stringWithFormat:@"组网完成 ---> 成功数：%lu，总耗时：%.2fs，平均耗时：%.2fs",(unsigned long)count, (endTime-beginTime),(endTime-beginTime)/count];
                    NSLog(@"%@",resultTips);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [FDSMeshApi refreshWorkNormal];
                        self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
                        [self.meshTool codingMeshData:self.meshTool.meshModel];
                        if (finish) {
                            [SVProgressHUD showSuccessWithStatus:resultTips];
                            [self.navigationController popViewControllerAnimated:YES];
                        } else {
                            [SVProgressHUD showErrorWithStatus:@"组网失败！"];
                        }
                    });
                }
            }];
        }
    }
}
- (void)startFastProvision:(NSArray *)deviceList{
    [SVProgressHUD show];
    __block NSTimeInterval beginTime = [[NSDate date] timeIntervalSince1970];
    // 注：Fast Proviosn支持000055及以上版本的设备，否则报错
    [FDSMeshApi startAddDeviceToNetWork_Fast:deviceList progressAction:^(CGFloat progress, NSArray * _Nonnull macList) {
        [SVProgressHUD showProgress:progress status:[NSString stringWithFormat:@"组网进度：%.0f%@, 配置节点：%lu/%lu",progress*100.0, @"%",(unsigned long)macList.count, (unsigned long)deviceList.count]];
    } resultAction:^(BOOL finish, NSArray * _Nonnull addrList) {
        NSInteger count = addrList.count;
        NSTimeInterval endTime = [[NSDate date] timeIntervalSince1970];
        NSString *resultTips = [NSString stringWithFormat:@"组网完成 ---> 成功数：%lu，总耗时：%.2fs，平均耗时：%.2fs",(unsigned long)count, (endTime-beginTime),(endTime-beginTime)/count];
        NSLog(@"%@",resultTips);
        dispatch_async(dispatch_get_main_queue(), ^{
            [FDSMeshApi refreshWorkNormal];
            self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
            [self.meshTool codingMeshData:self.meshTool.meshModel];
            if (finish) {
                [SVProgressHUD showSuccessWithStatus:resultTips];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [SVProgressHUD showErrorWithStatus:@"组网失败！"];
            }
        });
    }];
}
- (IBAction)clickSelectAllBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.selectDeviceList setArray:self.peripheralList];
    } else {
        [self.selectDeviceList removeAllObjects];
    }
    NSLog(@"选择的设备数：%lu",(unsigned long)self.selectDeviceList.count);
    [self.tableview reloadData];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.peripheralList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchDeviceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SearchDeviceTableViewCell class])];
    if (!cell){
        cell = [[NSBundle mainBundle] loadNibNamed:@"SearchDeviceTableViewCell" owner:nil options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CBPeripheral *peripheral = self.peripheralList[indexPath.row];
    cell.titleLabel.text = peripheral.device_name;
    cell.subTitleLabel.text = [NSString stringWithFormat:@"Type:%@-%@, R:%@, V:%@-%ld", peripheral.device_type, peripheral.device_macAddress, peripheral.device_rssi, peripheral.device_pa_value, (long)peripheral.device_firmwareVersion.integerValue];
    cell.iconImageview.image = [UIImage imageNamed:@"setting_05"];
    if ([self.selectDeviceList containsObject:peripheral]) {
        cell.selectImageview.image = [UIImage imageNamed:@"setting_02"];
    } else {
        cell.selectImageview.image = [UIImage imageNamed:@"setting_01"];
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CBPeripheral *peripheral = self.peripheralList[indexPath.row];
    if ([self.selectDeviceList containsObject:peripheral]) {
        [self.selectDeviceList removeObject:peripheral];
    } else {
        [self.selectDeviceList addObject:peripheral];
    }
    [self.tableview reloadData];
}

@end
